import ROSLIB from "roslib";

/**
 * 获取节点列表，获取成功返回真值
 * @param {ROSLIB.Ros} roslink Ros链接对象
 * @param {Object} self 回调函数的参数，可传入组件环境指针this
 * @param {function} callback 回调函数
 */
function getNodeList(roslink = null, self, callback) {
  // console.log(roslink.isConnected);
  if (roslink.isConnected) {
    var listClient = new ROSLIB.Service({
      ros: roslink,
      name: "/rosapi/nodes",
      serviceType: "rosapi/Nodes",
    });

    var request = new ROSLIB.ServiceRequest({});

    listClient.callService(
      request,
      function (result) {
        // callback success
        var array = result.nodes;
        callback(self, array);
      },
      function () {
        // callback failed
        console.log("Service Request failed");
        var failedArray = ["Service Request failed", "也许是连接中断"];
        callback(self, failedArray);
      }
    );
    return true;
  } else {
    var failedArray = ["Service Request failed", "连接中断,请检查连接"];
    callback(self, failedArray);
    return false;
  }
}

/**
 * 获取目标链接中目标节点的信息
 * @param {ROSLIB.Ros} roslink Ros链接
 * @param {String} nodename 节点名
 * @param {Object} self 回调函数参数，可传入组件环境指针this
 * @param {function} callback 回调函数
 */
function getNodeDetails(roslink = null, nodename, self, callback) {
  if (roslink.isConnected) {
    var listClient = new ROSLIB.Service({
      ros: roslink,
      name: "/rosapi/node_details",
      serviceType: "rosapi/NodeDetail",
    });

    var request = new ROSLIB.ServiceRequest({
      node: nodename
    });

    listClient.callService(
      request,
      function (result) {
        // callback success
        callback(self, result);
      }
    );
    return true;
  } else {
    var failedArray = ["Service Request failed", "连接中断,请检查连接"];
    callback(self, failedArray);
    return false;
  }
}

export { getNodeList, getNodeDetails };
